const MQTT_IP = '1.14.48.246:8083/mqtt' //mqtt地址端口

const MQTT_OPTIONS = {
	connectTimeout: 5000,
	clientId: v4(),
	username: '',
	password: '',
	clean: true
}

import {
	v4
} from 'uuid';
var mqtt = require('mqtt/dist/mqtt.js')

function MyMqtt() {
	this.options = MQTT_OPTIONS;
	console.log("option:" + JSON.stringify(this.options))
	this.mqttBrokerIp = MQTT_IP;
	this.client = null;
	this.connected = false;
	this.prefix = "esp8266/"
	this.topicList = [];
	this.onConnect = ()=>{
		console.log('connect to server:'+this.mqttBrokerIp+' successfully.')
	}
	this.onConnectFaild = (e)=>{
		console.log('connect to server:'+this.mqttBrokerIp+' faild.')
	}
	this.onExit = ()=>{
		console.log('exit mqtt.connect close.')
	}
}

MyMqtt.prototype.isConnected = function() {
	return this.connected;
}

MyMqtt.prototype.connect = function() {
	let that = this;
	// #ifdef H5
	this.client = mqtt.connect('ws://' + this.mqttBrokerIp, this.options)
	// #endif
	// #ifdef MP-WEIXIN||APP-PLUS
	this.client = mqtt.connect('wx://' + this.mqttBrokerIp, this.options)
	// #endif
	// this.client.on('connect', function() {
	// 	console.log('连接成功')
	// 	that.client.subscribe("that/topic", function(err) {
	// 		if (!err) {
	// 			console.log('订阅成功')
	// 		}
	// 	})
	// }).on('reconnect', function(error) {
	// 	console.log('正在重连...', that.topic)
	// }).on('error', function(error) {
	// 	console.log('连接失败...', error)
	// }).on('end', function() {
	// 	console.log('连接断开')
	// }).on('message', function(topic, message) {
	// 	console.log('接收推送信息：', message.toString())
	// })
}

MyMqtt.prototype.login = function(user, pwd) {
	if(user){
		this.options.username = user;
	}
	if(pwd){
		this.options.password = pwd;
	}
	//console.log("option:" + JSON.stringify(this.options))
	this.connect()
	this.client.on('connect', () => {
		this.connected = true;
		this.onConnect();
		// this.client.subscribe("esp8266/test", (err) => {
		// 	if (!err) {
		// 		console.log('连接成功，订阅正常！')
		// 		this.connected = true;
		// 	} else {
		// 		console.log('subscribe error:' + JSON.stringify(err))
		// 	}
		// });
	}).on('reconnect', (error)=>{
		console.log('正在重连...', that.topic)
	}).on('error', (error)=> {
		console.log('连接失败...', error)
		this.onConnectFaild(error);
	}).on('end', ()=> {
		console.log('连接断开')
		this.onExit();
	}).on('message', (topic, message)=>{
		for (let i in this.topicList) {
			let item = this.topicList[i];
			if (item.topic == topic) {
				//item.callFunc('test',topic,message);
				let ret = this.splitTopicWithId(topic);
				if(!ret.status){
					console.log('device id:'+ret.id+' topic:'+ret.topic)
					item.callFunc(ret.id,topic,message);
				}
				console.log(topic)
			}
		}
		console.log('接收推送信息：', message.toString())
	})
}

MyMqtt.prototype.close = function(){
	console.log("finish mqtt comnication")
	this.client.end(false, () => {
		console.log("断开成功！")
		this.client = null;
		this.connected = false;
	})
}

MyMqtt.prototype.findTopic= function(topic) {
	for (let i in this.topicList) {
		let item = this.topicList[i];
		if (item.topic == topic) {
			return i;
		}
	}
	return -1;
}

MyMqtt.prototype.addTopic = function(deviceId,topic,call_func){
	let new_topic = this.getTopicWithId(deviceId,topic);	
	//console.log('add topic:'+new_topic);
	let find = this.findTopic(new_topic)
	if( find == -1){
		let item = {'topic':new_topic,'callFunc':call_func}
		this.topicList.push(item);
		//this.client.subscribe(topic)
		this.subscribeWithId(deviceId,topic)
		
	}else{
		//console.log('find id&topic exist in:'+find)
		this.topicList[find].callFunc = call_func;
		this.subscribeWithId(deviceId,topic)
	}
}

MyMqtt.prototype.getTopicWithId = function(deviceId,topic){
	//将ID与topic组合在一起
	if(topic[0] == '/'){
		//console.log('right: '+topic.slice(1,topic.length))
		topic = topic.slice(1,topic.length);
	}
	let prefix = 'esp8266/'+deviceId+'/'+topic;
	return prefix;
}

MyMqtt.prototype.splitTopicWithId = function(topic){
	let ret = {
		'status':0,
		'id':'',
		'topic':''
	}
	if(!topic || topic.length==0){
		ret.status = -1;
		return ret;
	}
	if(topic.indexOf(this.prefix) == 0 ){
		//console.log('topic:'+topic)
		let new_topic = topic.slice(this.prefix.length,topic.length)
		//console.log('new :'+new_topic)
		let index = new_topic.indexOf('/');
		if(index == -1){
			console.log('topic:'+topic+'not found id or sub topic')
			ret.status = 2;
			return ret;
		}
		//console.log(index)
		let id = new_topic.slice(0,index);
		//console.log(id);
		let subtopic = new_topic.slice(index+1,new_topic.length);
		//console.log(subtopic)
		ret.id = id;
		ret.topic = subtopic;
		ret.status = 0;
		return ret;		
	}else{
		console.log('topic:'+topic+' not support.should start with '+this.prefix)
		ret.status = 1;
		return ret;
	}
}

MyMqtt.prototype.publishWithId = function(deviceId, topic, payload, qos = 0, reatin = false){
	//console.log('publish id:'+deviceId+',topic:'+topic+',payload:'+payload)
	topic = this.getTopicWithId(deviceId,topic);
	console.log("publish topic:" + topic)
	this.client.publish(topic, payload, {
		qos: qos,
		retain: reatin
	})
}

MyMqtt.prototype.subscribeWithId = function(deviceId,topic,qos=0){
	//console.log('subscribe id:'+deviceId+',topic:'+topic)
	topic = this.getTopicWithId(deviceId,topic);
	console.log("subscribe topic:" + topic)
	this.client.subscribe(topic, {
		qos: qos
	});
}

module.exports.MyMqtt = MyMqtt
